<template>
  <div>
    <slot/>
    <slot name="empty">
      <f-empty v-if='status==="empty"'>{{ showText.empty }}</f-empty>
    </slot>
    <div class="load-more">
      <div class="end" ref="end" :style="{top: `-${reachBottomDistance}px`}"></div>
      <div class="font12 gray pointer" v-if='status==="more"' @click="loadMore">{{ showText.more }}</div>
      <f-loading-2 v-else-if='status==="loading"'/>
      <div class="font12 gray" v-else-if='status==="noMore"'>{{ showText.noMore }}</div>
    </div>
  </div>
</template>

<script>
import FLoading2 from './loading/loading-2';

export default {
  name: 'f-infinite-load-2',
  components: {FLoading2},
  props: {
    /**
     * 加载状态：more-还有更多；loading-加载中；noMore-没有更多了；empty-空
     */
    status: {
      type: String,
      required: true,
      default: 'more',
      validator: function (value) {
        return ['more', 'loading', 'noMore', 'empty'].indexOf(value) !== -1;
      }
    },
    contentText: {
      type: Object,
      default: () => ({})
    },
    reachBottomDistance: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      initFlag: false
    };
  },
  computed: {
    showText() {
      let defaultText = {more: '点击加载更多', loading: '正在加载...', noMore: '没有更多数据了', empty: '暂无数据'};
      return {...defaultText, ...this.contentText};
    }
  },
  methods: {
    loadMore() {
      if (this.status === 'more') {
        this.$emit('loadMore');
      }
    },
    init() {
      let intersectionObserver = new IntersectionObserver(entries => {
        entries.forEach(entry => {
          if (!this.initFlag) this.initFlag = true;
          if (entry.isIntersecting && this.status === 'more') {
            this.$emit('loadMore');
          }
        });
      });
      intersectionObserver.observe(this.$refs.end);
    }
  },
  mounted() {
    this.init();
  }
};
</script>

<style lang="scss" scoped>
.load-more {
  text-align: center;
  height: 0.5rem;
  line-height: 0.5rem;
  position: relative;
  .end {
    position: absolute;
    left: 0;
  }
}
</style>
